package com.xhxi.photobooker.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


import com.xhxi.photobooker.entity.Order;
import com.xhxi.photobooker.entity.Photographer;
import com.xhxi.photobooker.enums.OrderStatus;
import com.xhxi.photobooker.mapper.OrderMapper;
import com.xhxi.photobooker.mapper.PhotographerMapper;
import com.xhxi.photobooker.service.OrderService;
import com.xhxi.photobooker.service.PhotographerService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {



    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private PhotographerMapper photographerMapper;

    /*用户查询所有订单*/

    public List<Order> listUserOrders(Long userId) {
        return orderMapper.selectByUserId(userId);
    }




    @Transactional
    public Order createOrder(Order order) {
        order.setCreateTime(LocalDateTime.now());
        order.setStatus(OrderStatus.PENDING); // 待支付状态

        // 检查摄影师档期
        boolean isAvailable = checkPhotographerAvailability(
                order.getPhotographerId(),
                order.getShootingTime()
        );

        if (!isAvailable) {
            throw new RuntimeException("摄影师该时段不可用");
        }

        orderMapper.insert(order);
        return order;
    }

    @Override
    public Order selectByOrderId(Long orderId) {
        return orderMapper.selectById(orderId);
    }


    @Transactional
    public boolean finishOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        order.setStatus(OrderStatus.COMPLETED);
        //把订单状态修改为已完成
        orderMapper.updateById(order);
        
        // 更新摄影师的完成订单数
        updatePhotographerOrderCount(order.getPhotographerId());
        
        return true;
    }


    public Order cancelOrder(Long orderId, Long userId) {
        Order order = orderMapper.selectById(orderId);

        if (order == null || !order.getUserId().equals(userId)) {
            throw new RuntimeException("订单不存在或无权限操作");
        }

        // 只有特定状态的订单可以取消
        if (OrderStatus.PENDING!=(order.getStatus()) && OrderStatus.CONFIRMED.equals(order.getStatus())) {
            throw new RuntimeException("该订单状态不可取消");
        }

        order.setStatus(OrderStatus.CANCELED);
        order.setUpdateTime(LocalDateTime.now());
        orderMapper.updateById(order);

        // 释放摄影师档期
        // releasePhotographerSlot(order.getPhotographerId(), order.getShootingTime());

        return order;
    }

    /*摄影师查询所有订单*/
    @Override
    public List<Order> listOrdersByPhotographerId(Long photographerId) {
        return orderMapper.selectOrderByPhotographerId(photographerId);
    }
    
    /*获取摄影师完成的订单数*/
    @Override
    public Integer getCompletedOrderCount(Long photographerId) {
        return orderMapper.countCompletedOrdersByPhotographerId(photographerId);
    }
    
    /*获取所有订单*/
    @Override
    public List<Order> getAllOrders() {
        return orderMapper.selectList(null);
    }

    @Override
    public List<Order> getRecentOrders(int limit) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time").last("LIMIT " + limit);
        return orderMapper.selectList(wrapper);
    }

    /*更新摄影师的完成订单数*/
    private void updatePhotographerOrderCount(Long photographerId) {
        Integer completedCount = getCompletedOrderCount(photographerId);
        Photographer photographer = photographerMapper.selectById(photographerId);
        if (photographer != null) {
            photographer.setOrderCount(completedCount);
            photographerMapper.updateById(photographer);
        }
    }

    private boolean checkPhotographerAvailability(Long photographerId, LocalDateTime shootingTime) {
        // 检查摄影师在指定时间是否已有订单
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("photographer_id", photographerId)
                .eq("shooting_time", shootingTime)
                .notIn("status", "CANCELED", "FAILED");

        return !orderMapper.exists(queryWrapper);
    }
}